package com.caishi.lkx.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.caishi.lkx.user.config.ThirdOauthConfig;
import com.zzw.common.exception.BizException;
import com.zzw.common.exception.BizRuntimeException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author huangpeng
 * @Description //
 * @Date 2022/8/11 13:24
 **/

@Component
public class WeChatUtil {

    private static ThirdOauthConfig thirdOauthConfig;
    private static RedisTemplate<String, String> redisTemplate;
    private static final String WECHAT_XCX_ACCESSTOKEN_KEY = "WECAT:XCX:ACCESSTOKEN";

    @Resource
    public void setThirdOauthConfig(ThirdOauthConfig thirdOauthConfig) {
        WeChatUtil.thirdOauthConfig = thirdOauthConfig;
    }

    @Resource
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        WeChatUtil.redisTemplate = redisTemplate;
    }

    public static JSONObject decrypt(String sessionKey, String encryptedData, String iv) throws BizException {
        try {
            AES aes = new AES(Mode.CBC, Padding.NoPadding, Base64.decode(sessionKey), Base64.decode(iv));
            byte[] resultByte = aes.decrypt(Base64.decode(encryptedData));
            if (null != resultByte && resultByte.length > 0) {
                String str = new String(resultByte, StandardCharsets.UTF_8);
                return JSONUtil.parseObj(str);
            }
            return null;
        } catch (Exception e) {
            throw new BizException("解码错误");
        }
    }

    public static String getXcxAccessToken() {
        String accessToken = redisTemplate.opsForValue().get(WECHAT_XCX_ACCESSTOKEN_KEY);
        if (StrUtil.isNotBlank(accessToken)) return accessToken;
        String appid = thirdOauthConfig.getWeCatXcxAppid();
        String secret = thirdOauthConfig.getWeCatXcxSecret();
        String accessTokenUrl = thirdOauthConfig.getWeCatXcxAccessTokenUrl();
        String format = String.format(accessTokenUrl, appid, secret);
        String resp = HttpUtil.get(format);
        JSONObject jsonObject = JSONUtil.parseObj(resp);
        accessToken = jsonObject.getStr("access_token");
        String expiresIn = jsonObject.getStr("expires_in");
        if (StrUtil.isBlank(accessToken)) {
            throw new BizRuntimeException("access_token获取失败");
        } else {
            redisTemplate.opsForValue().set(WECHAT_XCX_ACCESSTOKEN_KEY, accessToken, Long.parseLong(expiresIn) - 1, TimeUnit.SECONDS);
        }
        return accessToken;
    }

    public static InputStream createXcxQRCode(Map<String, Object> param) {
        String weCatXcxQRCodeUrl = thirdOauthConfig.getWeCatXcxQRCodeUrl();
        String format = String.format(weCatXcxQRCodeUrl, getXcxAccessToken());
        HttpRequest httpRequest = HttpUtil.createPost(format);
        httpRequest.body(JSONUtil.toJsonStr(param));
        HttpResponse execute = httpRequest.execute();
        String header = execute.header(Header.CONTENT_TYPE);
        if (!header.equals("image/jpeg")) {
            throw new BizRuntimeException("获取二维码失败");
        }
        return execute.bodyStream();
    }
//
//    public static void main(String[] args) throws BizException {
//        System.out.println(decrypt("pxfUAl+i1/NjnSfDF7s+fw==","C981z9/gHMfiG5PSuxgd04pxTcS0p1w0DIMfG98BxN0NeLem5iT5mG+9j6I3bSsare7e515KBYhNIDth3T3xWwl269EywWwxm0ZMz8RB9YqnCIs065Nm/V0JN+TT0KNqYriiGTtpS9RLlu9t1am+DBVKbc74wMWSxRE/9qkmqjOwuh3tLFJA7BbeoXY7PDkGH2OA+da1HRuQtkFVDyGupQ==","5FXvQ+nih/oqofj7yt69NQ=="));
//
//    }

}
